/**
 * 更新图层顺序
 * @param mapBoxInstance
 * @param orderLayers
 */
function updateMapLayerOrder(mapBoxInstance: any, orderLayers: any) {
  const sortLayerByOrder = orderLayers.sort(
    (a: any, b: any) => a.order - b.order
  )
  const needSortLayer: any[] = sortLayerByOrder
  for (let i: number = 0; i <= needSortLayer.length - 2; i += 1) {
    const layer1Id: string = `${needSortLayer[i].id}`
    const layer1LabelId: string = `label-${layer1Id}`
    const layer1ArrowId: string = `arrow-layer-${layer1Id}`
    const layer2Id: string = `${needSortLayer[i + 1].id}`
    const layer2LabelId: string = `label-${layer2Id}`
    const layer2ArrowId: string = `arrow-layer-${layer2Id}`

    const layer1: boolean = !!mapBoxInstance.getLayer(layer1Id)
    const layer1Label: boolean = !!mapBoxInstance.getLayer(layer1LabelId)
    const layer1Arrow: boolean = !!mapBoxInstance.getLayer(layer1ArrowId)
    const layer2: boolean = !!mapBoxInstance.getLayer(layer2Id)
    const layer2Label: boolean = !!mapBoxInstance.getLayer(layer2LabelId)
    const layer2Arrow: boolean = !!mapBoxInstance.getLayer(layer2ArrowId)
    if (layer1Label) {
      mapBoxInstance.moveLayer(layer1Id, layer1LabelId)
      if (layer1Arrow) {
        mapBoxInstance.moveLayer(layer1ArrowId, layer1LabelId)
      }
    } else if (layer1Arrow) {
      mapBoxInstance.moveLayer(layer1Id, layer1ArrowId)
    }

    if (layer1 && layer2) {
      mapBoxInstance.moveLayer(layer2Id, layer1Id)
    }
    if (layer2Label) {
      mapBoxInstance.moveLayer(layer2LabelId, layer1Id)
      if (layer2Arrow) {
        mapBoxInstance.moveLayer(layer2ArrowId, layer2LabelId)
      }
    } else if (layer2Arrow) {
      mapBoxInstance.moveLayer(layer2ArrowId, layer1Id)
    }
  }
}

export default updateMapLayerOrder
